//
//  QYXDailyDetailViewController.m
//  OpenYourEyes
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 Google AdWords. All rights reserved.
//

#import "QYXDailyDetailViewController.h"
#import "QYXDailyDetailCollectionViewCell.h"
#import "QYXTalkModel.h"
#import "QYXTalkReplyListModel.h"
#import "AppDelegate.h"
#import "QYXTalkDetailTableViewCell.h"
#import "QYXDailyViewController.h"
#import "MagicMoveBackTransition.h"

@interface QYXDailyDetailViewController () <UICollectionViewDelegate, UICollectionViewDataSource, PushVCByPlayButtonDelegate, UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate>


/** 评论的view */
@property (nonatomic, strong) UIView *talkView;
@property (nonatomic, strong) UITableView *talkTableView;
@property (nonatomic, strong) NSMutableArray *talkSource;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *talkLabel;
@property (nonatomic, strong) UILabel *writeLabel;
@property (nonatomic, strong) UIImageView *dismissImageView;
/** 评论的加载网络信息 */
@property (nonatomic, copy) NSString *webString;
@property (nonatomic, strong) MagicMoveBackTransition *backTransition;

@end

@implementation QYXDailyDetailViewController
- (void)dealloc
{
    _talkTableView.delegate = nil;
    _talkTableView.dataSource = nil;

    _mainCollectionView.delegate = nil;
    _mainCollectionView.dataSource = nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImage *image = [[UIImage imageNamed:@"back.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    [self createCollectionView];
    
}
#pragma mark -- 初始化界面
- (void)createCollectionView
{
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    [self.view addSubview:view];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(kScreenWidth, kScreenHeight - 64);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    //初始化collectionView
    self.mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64,kScreenWidth, kScreenHeight - 64) collectionViewLayout:flowLayout];
    self.mainCollectionView.pagingEnabled = YES;
    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    self.mainCollectionView.backgroundColor = [UIColor clearColor];
    self.mainCollectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_mainCollectionView];
    
    //注册cell
    [self.mainCollectionView registerClass:[QYXDailyDetailCollectionViewCell class] forCellWithReuseIdentifier:@"detailCell"];
    [self.mainCollectionView setContentOffset:CGPointMake(kScreenWidth * self.modelRow, 0)];
    
  

    
}
- (void)back
{
    AppDelegate *tempDelegate = [UIApplication sharedApplication].delegate;
        tempDelegate.tabBar.backView.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.delegate = self;
}
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                            animationControllerForOperation:(UINavigationControllerOperation)operation
                                                         fromViewController:(UIViewController *)fromVC
                                                           toViewController:(UIViewController *)toVC
{
    if ([toVC isKindOfClass:[QYXDailyViewController class]]) {
        self.backTransition = [[MagicMoveBackTransition alloc] init];
        return _backTransition;
    }
    return nil;
}
#pragma mark -- 导航眼点击按钮方法"

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.listDataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    QYXDailyDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"detailCell" forIndexPath:indexPath];
    QYXDailyItemListModel *model = [self.listDataSource objectAtIndex:indexPath.item];
    self.modelRow = indexPath.item;
    cell.topicsLabel = model.tags;
    cell.model = model;
    cell.delegate = self;
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -- 协议方法:
- (void)pushVCByTopListLabel:(NSInteger)index
{
    
}
- (void)pushVCByPlayImageView:(NSInteger)id
{
    
}
- (void)presentViewByTalkLabel:(NSInteger)talkID
{
    [self createTalkTableView:talkID];
}
- (void)presentViewByShareLabel
{
    
}

- (void)pushVCByVideoModel:(QYXDailyItemListModel *)model
{
    

    VideoFullScreenController *vc = [[VideoFullScreenController alloc] initWithQYXDailyItemListModel:model];
    [self presentViewController:vc animated:YES completion:nil];
}



#pragma mark -- 评论的视图和数据请求:
- (void)createTalkTableView:(NSInteger)talkID
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickedTap:)];
  
    self.talkView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)];
    self.talkView.backgroundColor = [UIColor clearColor];
    self.talkView.alpha = 0;
    [self.view addSubview:_talkView];
    
    
    /** 毛玻璃 */
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    visualView.frame = CGRectMake(0, self.talkView.frame.size.height / 2, kScreenWidth, self.talkView.frame.size.height / 2);
    visualView.userInteractionEnabled = YES;
    [self.talkView addSubview:visualView];
    
    
    UIView *blackView = [[UIView alloc] initWithFrame:self.talkView.bounds];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.3;
    [self.talkView addSubview:blackView];
    
    //创建View上的控件:
    self.dismissImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.talkView.frame.size.width / 2 - 15, 15, 30, 30)];
    self.dismissImageView.userInteractionEnabled = YES;
    [self.dismissImageView addGestureRecognizer:tap];
    self.dismissImageView.image = [UIImage imageNamed:@"down_jiantou"];
    [self.talkView addSubview:_dismissImageView];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.dismissImageView.frame.origin.y + self.dismissImageView.frame.size.height + 50, kScreenWidth, 20)];
    self.titleLabel.font = [UIFont fontWithName:@"FZLTZCHJW--GB1-0" size:15];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = 1;
    [self.talkView addSubview:_titleLabel];
    
    self.talkLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height + 15, kScreenWidth, 20)];
    self.talkLabel.font = [UIFont fontWithName:@"FZLTZCHJW--GB1-0" size:13];
    self.talkLabel.textAlignment = 1;
    self.talkLabel.textColor = [UIColor whiteColor];
    [self.talkView addSubview:_talkLabel];
    
    self.writeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.talkView.frame.size.height / 2 - 10 - 50, kScreenWidth - 20, 50)];
    self.writeLabel.font = [UIFont fontWithName:@"FZLTXIHJW--GB1-0" size:13];
    self.writeLabel.layer.borderColor = [UIColor whiteColor].CGColor;
    self.writeLabel.layer.borderWidth = 1.0;
    self.writeLabel.textAlignment = 1;
    self.writeLabel.textColor = [UIColor whiteColor];
    [self.talkView addSubview:_writeLabel];
    
    
    
    //初始化tableView
    self.talkTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.talkView.frame.size.height / 2, kScreenWidth, self.talkView.frame.size.height / 2) style:UITableViewStylePlain];
    self.talkTableView.showsVerticalScrollIndicator = NO;
    self.talkTableView.delegate = self;
    self.talkTableView.dataSource = self;
    self.talkTableView.backgroundColor = [UIColor clearColor];
    
    //自适应高度:
    self.talkTableView.estimatedRowHeight = 50;
    self.talkTableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.talkView addSubview:_talkTableView];
    self.talkSource = [NSMutableArray array];
    
    [self.talkTableView registerNib:[UINib nibWithNibName:@"QYXTalkDetailTableViewCell" bundle:nil] forCellReuseIdentifier:@"talkDetailCell"];
    
    [self createTableDataSource:talkID];
    
    /** 上拉加载下拉刷新 */
    self.talkTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getData:talkID];
    }];
    self.talkTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getMoreData];
    }];
}
#pragma mark -- 上拉加载下拉刷新
- (void)getData:(NSInteger)talkID
{
    [self.talkSource removeAllObjects];
    [self.talkTableView reloadData];
    [self createTableDataSource:talkID];
}
- (void)getMoreData
{
    [self createTalkMoreDataSource];
}
- (void)createTalkMoreDataSource
{

    [QYXNetTool getNetWithUrl:_webString urlBody:nil header:nil response:QYXJSON success:^(id result) {
        QYXTalkModel *model = [[QYXTalkModel alloc] initWithDic:result];
        if ([model.nextPageUrl isEqualToString:@""]) {
            self.webString = model.nextPageUrl;
        }
        for (NSDictionary *dic in model.replyList) {
            QYXTalkReplyListModel *talkModel = [[QYXTalkReplyListModel alloc] initWithDic:dic];
            [self.talkSource addObject:talkModel];
        }
        if (self.talkSource.count != 0) {
            self.talkLabel.text = [NSString stringWithFormat:@"- %ld 条评论 -", model.total];
            self.writeLabel.text = @"写下你的评论";
            [UIView animateWithDuration:1 animations:^{
                self.talkView.alpha = 1.0;
            }];
            [self.talkTableView reloadData];
            [self.talkTableView.mj_footer endRefreshing];
            [self.talkTableView.mj_header endRefreshing];
        }
    } failure:^(NSError *error) {
        
    }];
}
- (void)createTableDataSource:(NSInteger)loginID
{
    NSString *string = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/replies/video?_f=iphone&id=%ld&net=wifi&num=20&u=aafd829df8ff2d571a778ed3cca27eb68b16bd7d&v=2.2.0&vc=721", loginID];
    [QYXNetTool getNetWithUrl:string urlBody:nil header:nil response:QYXJSON success:^(id result) {
        
        QYXTalkModel *model = [[QYXTalkModel alloc] initWithDic:result];
        self.webString = model.nextPageUrl;
        for (NSDictionary *dic in model.replyList) {
            QYXTalkReplyListModel *talkModel = [[QYXTalkReplyListModel alloc] initWithDic:dic];
            [self.talkSource addObject:talkModel];
        }
        if (self.talkSource.count != 0) {
            self.talkLabel.text = [NSString stringWithFormat:@"- %ld 条评论 -", model.total];
            self.writeLabel.text = @"写下你的评论";
            [UIView animateWithDuration:1 animations:^{
                self.talkView.alpha = 1.0;
            }];
            [self.talkTableView reloadData];
            [self.talkTableView.mj_header endRefreshing];
            [self.talkTableView.mj_footer endRefreshing];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.talkSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    QYXTalkDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"talkDetailCell"];
    if (self.talkSource.count != 0) {
        
        QYXTalkReplyListModel *model = [self.talkSource objectAtIndex:indexPath.row];
        self.titleLabel.text = model.videoTitle;
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
    }
    return cell;
}
- (void)didClickedTap:(UITapGestureRecognizer *)tap
{
    [UIView animateWithDuration:1 animations:^{
        self.talkView.alpha = 0;
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.talkView removeFromSuperview];
    });
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
